<template>
  <q-layout
    view="lhr lpR lfr"
    class="bg-grey-1 text-grey"
    style="overflow-x: hidden"
  >
    <q-header elevated class="bg-white text-grey-8" height-hint="64">
      <header-page></header-page>
    </q-header>
    <aside-page></aside-page>
    <q-page-container>
      <transition name="leftInto">
        <router-view />
      </transition>
    </q-page-container>
    <q-footer reveal elevated>
      <div
        style="
          text-align: center;
          line-height: 40px;
          background-color: white;
          user-select: none;
        "
      >
        <span style="color: #999999; font-size: 12px"
          >Copyright © 2022–2023 SybioGene s.r.o. | Help | Support | SybioGene
          Privacy Policy | SybioGene Account
          Agreement| Build #2023.03-3111</span
        >
      </div>
    </q-footer>
    <el-dialog
      v-model="platformUploadStore.platformUploadModalShow"
      title="上传列表"
      width="60%"
      :modal="false"
      destroy-on-close
    >
      <el-select
        v-model="platformUploadStore.platformCurType"
        class="m-2"
        placeholder="Select"
        size="default"
        style="margin-bottom: 23px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <template v-if="platformUploadStore.platformCurType === 'dataset'">
        <el-table
          :data="platformUploadStore.platformUploadList"
          height="377"
          style="width: 100%"
          :header-cell-style="{
            background: '#f9f9f9',
            color: '#333333',
            fontWeight: '500',
            fontSize: '14px',
            textAlign: 'left',
            height: '56px',
          }"
        >
          <el-table-column
            prop="row_name"
            label="文件名称"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column prop="total_size_calc" label="文件大小" />
          <el-table-column prop="dataset_title" label="所属数据集" />
          <el-table-column prop="version_title" label="所属版本" />
          <el-table-column prop="create_time" label="上传时间" width="180" />
          <el-table-column label="上传状态" width="147">
            <template #default="scope">
              <StatusBoxCpn
                :status="scope.row.status"
                :label="
                  scope.row.progress == 0 && scope.row.status != 'failure'
                    ? 'queueing'
                    : scope.row.status
                "
                :gap="5"
              />
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="上传进度" width="120">
            <template #default="scope">
              <template v-if="scope.row.status != 'failure'">
                <template v-if="scope.row.progress == 100"> 100% </template>
                <template v-else-if="scope.row.progress == 0">
                  排队中……
                </template>
                <el-progress
                  v-else
                  :stroke-width="10"
                  :percentage="scope.row.progress"
                />
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template
        v-else-if="platformUploadStore.platformCurType === 'featureSet'"
      >
        <el-table
          :data="platformFeatureSetUploadStore.platformUploadList"
          height="377"
          style="width: 100%"
          :header-cell-style="{
            background: '#f9f9f9',
            color: '#333333',
            fontWeight: '500',
            fontSize: '14px',
            textAlign: 'left',
            height: '56px',
          }"
        >
          <el-table-column
            prop="row_name"
            label="文件名称"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column prop="total_size_calc" label="文件大小" />
          <el-table-column prop="feature_set_title" label="所属特征集" />
          <el-table-column prop="create_time" label="上传时间" width="180" />
          <el-table-column label="上传状态">
            <template #default="scope">
              <StatusBoxCpn
                :status="scope.row.status"
                :label="
                  scope.row.progress == 0 && scope.row.status != 'failure'
                    ? 'queueing'
                    : scope.row.status
                "
                :gap="5"
              />
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="上传进度" width="180">
            <template #default="scope">
              <template v-if="scope.row.status != 'failure'">
                <template v-if="scope.row.progress == 100"> 100% </template>
                <template v-else-if="scope.row.progress == 0">
                  排队中……
                </template>
                <el-progress
                  v-else
                  :stroke-width="10"
                  :percentage="scope.row.progress"
                />
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-dialog>
    <el-dialog
      v-model="projectStore.blockVisible"
      :title="$t('selectProjects')"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div class="dialogContent">
        <div class="dialogLeft">{{ $t('selectProjectEntry') + ':' }}</div>
        <div class="dialogRight">
          <el-menu
            :default-active="activeIndex"
            active-text-color="#0000ff"
            background-color="#fff"
            class="el-menu-demo"
            text-color="#000"
            unique-opened="true"
            @select="handleSelect"
          >
            <el-sub-menu index="1">
              <template #title>
                <el-icon>
                  <House />
                </el-icon>
                <span>{{ $t('allItems') }}</span>
              </template>
              <template
                v-for="(project, index) in collectProjects"
                :key="project.id"
              >
                <el-menu-item
                  :index="'1-' + index + 1"
                  @click="getProjectId(project)"
                  >{{ project.title }}
                </el-menu-item>
              </template>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <el-icon>
                  <Folder />
                </el-icon>
                <span>{{ $t('theProjectICreated') }}</span>
              </template>
              <template
                v-for="(project, index) in creatorList"
                :key="project.id"
              >
                <el-menu-item
                  :index="'2-' + index + 1"
                  @click="getProjectId(project)"
                  >{{ project.title }}
                </el-menu-item>
              </template>
            </el-sub-menu>
            <el-sub-menu index="3">
              <template #title>
                <el-icon>
                  <User />
                </el-icon>
                <span>{{ $t('theProjectIManage') }}</span>
              </template>
              <template v-for="(project, index) in adminList" :key="project.id">
                <el-menu-item
                  :index="'3-' + index + 1"
                  @click="getProjectId(project)"
                  >{{ project.title }}
                </el-menu-item>
              </template>
            </el-sub-menu>
            <el-sub-menu index="4">
              <template #title>
                <el-icon>
                  <User />
                </el-icon>
                <span>{{ $t('projectsIAmInvolvedIn') }}</span>
              </template>
              <template
                v-for="(project, index) in participateList"
                :key="project.id"
              >
                <el-menu-item
                  :index="'4-' + index + 1"
                  @click="getProjectId(project)"
                  >{{ project.title }}
                </el-menu-item>
              </template>
            </el-sub-menu>
          </el-menu>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">{{ $t('cancle') }}</el-button>
          <el-button @click="toEnterProject" type="primary">{{
            $t('enteringTheProject')
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </q-layout>
</template>

<script setup lang="ts">
import StatusBoxCpn from 'components/StatusBoxCpn.vue';
import { ElMessage } from 'element-plus';
import { getProjectList, isQuickStart } from 'src/api/project';
import { isMemberInterface } from 'src/api/user';
import AsidePage from 'src/components/layouts/AsidePage.vue';
import HeaderPage from 'src/components/layouts/HeaderPage.vue';
import { dataSetStore } from 'src/stores/dataSet';
import { useMenuStore } from 'src/stores/menu';
import { useCleanErrorUploadQueue } from 'src/utils/useCleanErrorUploadQueue';
import { useScheduler } from 'src/utils/useScheduler';
import { useWatchProgress } from 'src/utils/useWatchProgress';
import { useCurrentProjectStore } from 'stores/current-project';
import { usePlatformFeatureSetUploadStore } from 'stores/platform-featureset-upload';
import { usePlatformUploadStore } from 'stores/platform-upload';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useDelErrorUpload } from '../utils/useDelErrorUploadQueue';

const store = dataSetStore();
const collectProjects = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const tab = ref('participation');

const menuStore = useMenuStore();
const platformUploadStore = usePlatformUploadStore();
const platformFeatureSetUploadStore = usePlatformFeatureSetUploadStore();

const router = useRouter();
let creatorList = ref([]); //我创建的
let adminList = ref([]); //我管理的
let participateList = ref([]); //我参与的
let projectId = ref(0); //项目的id
const projectStore = useCurrentProjectStore();

const options = [
  {
    value: 'dataset',
    label: '数据集',
  },
  {
    value: 'featureSet',
    label: '特征集',
  },
];
onMounted(() => {
  getQuickStartState();
});

onMounted(async () => {
  await Promise.all([
    platformUploadStore.initPlatformUploadList(),
    platformFeatureSetUploadStore.initPlatformUploadList(),
  ]);
});

// 获取快速入门状态
function getQuickStartState() {
  isQuickStart().then((res: any) => {
    store.setIsQuickStart(res.data.quick_start);
  });
}

//创建项目 end
getProjects();

//判断页面初始化时，当前路由是否包含当前项目，如果存在，那么删除
havCurrentProject();

useWatchProgress('fileNoChunks', 'dataset');
useWatchProgress('fileChunks', 'dataset');
useWatchProgress('fileNoChunks', 'featureSet');
useWatchProgress('fileChunks', 'featureSet');
useCleanErrorUploadQueue('dataset');
useCleanErrorUploadQueue('featureSet');
useScheduler('dataset');
useScheduler('featureSet');
useDelErrorUpload('dataset');
useDelErrorUpload('featureSet');

function havCurrentProject() {
  let menuArrayList = menuStore.menuItems.filter((item: any) => {
    if (item.currentProject) {
      return true;
    } else {
      return false;
    }
  });
  if (menuArrayList.length > 0) {
    menuStore.deleteMenuItems();
  }
}

function getProjects() {
  loading.value = true;
  getProjectList()
    .then((res) => {
      collectProjects.value = res.data;
      menuStore.setAllMenuList(res.data);
      creatorList.value = res.data.filter(
        (item: any) => item.category.is_creator
      ); //我创建的
      adminList.value = res.data.filter((item: any) => item.category.is_admin); //我管理的
      participateList.value = res.data.filter(
        (item: any) => item.category.only_participate
      ); //我参与的
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
}

function toEnterProject() {
  isMember(projectId.value);
  projectStore.setCurrentProject(projectId.value);
  projectStore.setBlockVisible(false);
}

function closeDialog() {
  projectStore.setBlockVisible(false);
}

function isMember(id: any) {
  isMemberInterface(id)
    .then((res) => {
      const menuList = JSON.parse(JSON.stringify(collectProjects.value));
      const current = menuList.filter((item: any) => item.id === id); //当前项目
      const removeCurrntProject = menuList.filter(
        (item: any) => item.id !== id
      ); //除了当前项目外全部的其他项目
      let obj = {
        currentProject: true,
        ...current[0],
        children: removeCurrntProject,
      };
      menuStore.addMenuItems(obj);
      menuStore.setCurrentProject(obj);
      console.log('store.isQuickStart', store.isQuickStart);
      if (store.isQuickStart && !JSON.parse(localStorage.user).is_admin) {
        router.push({ name: 'quick-start', params: { project_id: id } });
      } else {
        router.push({ name: 'project-detail', params: { project_id: id } });
      }
      let userInfo = JSON.parse(localStorage.getItem('user') as any);
      userInfo['status'] = res.data.status;
      localStorage.setItem('user', JSON.stringify(userInfo));
    })
    .catch(() => {
      ElMessage.error('获取项目创建人或管理员接口报错！');
    });
}

const activeIndex = ref('1-1');

const handleSelect = (key: any, keyPath: any) => {
  activeIndex.value = keyPath[1];
};
const getProjectId = (project: any) => {
  projectId.value = JSON.parse(JSON.stringify(project)).id;
};
</script>

<style lang="scss">
.q-focus-helper::after {
  background-color: unset;
}

.q-expansion-item .q-item {
  border-radius: 5px 5px;
  min-height: 40px;
}

.q-tab-panel {
  padding-top: 5px;
}

.drawer-project-title {
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  word-break: break-all;
}

.el-menu--horizontal {
  height: 40px;
  border: unset;

  .el-sub-menu__title {
    color: $grey-8 !important;
  }
}

.el-divider {
  margin: 10px 0;
}

// dialog
.star {
  width: 25px;
  height: 25px;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 0;
}

::v-deep .el-card__body {
  padding: 0;
}

::v-deep .el-dialog__header {
  margin: 0;
  border-bottom: 1px solid;
}

::v-deep .q-item {
  background-color: #ffffff;
}

::v-deep .el-menu {
  border: none;
}

::v-deep .el-dialog__body {
  padding-top: 0;
}

.el-menu ::v-deep(.el-sub-menu.is-active > .el-sub-menu__title) {
  color: #0000ff !important;
}

.project-page .q-tab {
  height: 40px;
  font-size: 16px;
}

.createProjectDialogFooter {
  display: flex;
  position: absolute;
  right: 0 !important;
  bottom: 0;
  width: 100%;
  border: none !important;

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid;
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}

.dialogContent {
  display: flex;
  justify-content: space-between;
  vertical-align: top;
  width: 550px;
  margin: 0 auto;
}

.dialogLeft {
  flex: 1;
  text-align: right;
  padding-top: 17px;
  font-size: 13px;
  color: #1d1d1d;
  font-weight: bold;
}

.dialogRight {
  flex: 3;
  height: 230px;
  overflow: auto;
}

.acitve-item {
  svg,
  .q-item__section--avatar i {
    color: $primary;
  }
}

.createProjectDialogFooter {
  display: flex;
  justify-content: flex-end;
  position: absolute;
  bottom: 20px;
  width: 100%;
  padding-right: 20px;
  border-top: none;
  box-sizing: border-box;

  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }

  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid;
  }

  .button:nth-child(2) {
    color: #1b5bd8;
  }
}

//.dialog-footer {
//  display: flex;
//  position: absolute;
//  left: 0;
//  bottom: 0;
//  width: 100%;
//  border-top: 1px solid;
//
//  .button {
//    cursor: pointer;
//    width: 50%;
//    margin: 0;
//    border: none;
//    text-align: center;
//    line-height: 40px;
//  }
//
//  .button:nth-child(1) {
//    color: #1d1d1d;
//    border-right: 1px solid;
//  }
//
//  .button:nth-child(2) {
//    color: #1b5bd8;
//  }
//}
</style>
